<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;


use think\Log;

class Line extends Api
{
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['*'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];

    public function _initialize()
    {
        parent::_initialize();

    }

    //http://wu.test/api/line/linelogin
    public function linelogin() {

//        $code = $this->request->request('code', '');
//
//        if (empty($code)) {
//            unset($_SESSION['lineLoginInfo']);
//            $code = $_GPC['code'];
//            $state = $_GPC['state'];//colin600
//
//            $redirect_uri = $_W['siteroot']."linelogin.php";
////    $payload = [
////        'grant_type' => 'authorization_code',
////        'code' => $code,
////        'redirect_uri' => $redirect_uri,
////        'client_id' => '1606890616',
////        'client_secret' => '498512f59c2e5b08d4a7cdab9ce3340c'
////    ];
//            $client_id = "1606890616";
//            $client_secret = "498512f59c2e5b08d4a7cdab9ce3340c";
//            if (strpos($_W['siteroot'], 'megotw') === false) {
//                //正式服务器
//                $client_id = "1654420953";
//                $client_secret = "ae5eb13e58ae37fec83456c702ffb7e0";
//
//                $account = pdo_get('account_wechats', array('uniacid' => 2));
//                if ($account && !empty($account['line_login_channel_id'])) {
//                    $client_id = $account['line_login_channel_id'];
//                    $client_secret = $account['line_login_channel_secret'];
//                }
//
//            }
//
//            $payload = "grant_type=authorization_code&client_id=".$client_id."&client_secret=".$client_secret."&code="
//                . $code . "&redirect_uri=" . $redirect_uri;
//            logging_run(array('colin5556' => $payload));
//
//            $ch = curl_init();
//            curl_setopt($ch, CURLOPT_URL, 'https://api.line.me/oauth2/v2.1/token');
//            curl_setopt($ch, CURLOPT_POST, true);
//            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
//            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
//            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
//            curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
//            curl_setopt($ch, CURLOPT_HTTPHEADER, [
//                'Content-Type: application/x-www-form-urlencoded'
//            ]);
//            curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 15);
//            curl_setopt($ch, CURLOPT_TIMEOUT, 15);
//            $ret = curl_exec($ch);
//            $err = curl_error($ch);
//
//            if (FALSE === $ret || !empty($err)) {
//                $errno = curl_errno($ch);
//                $info = curl_getinfo($ch);
//                logging_run(array('colin5557' => $err));
//            }
//            curl_close($ch);
//            logging_run(array('colin6000' => $ret, 'colin6001' => $err));
//
//            $ret = json_decode($ret, true);
//
//            if (isset($ret['access_token'])) {
//                $access_token = $ret['access_token'];
//                logging_run(array('colin10' => $access_token));
//
//                $ch = curl_init();
//                curl_setopt($ch, CURLOPT_URL, 'https://api.line.me/v2/profile');
//                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//                curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
//                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
//                curl_setopt($ch, CURLOPT_HTTPHEADER, [
//                    'Authorization: Bearer ' . $access_token
//                ]);
//                curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 15);
//                curl_setopt($ch, CURLOPT_TIMEOUT, 15);
//                $ret = curl_exec($ch);
//                $err = curl_error($ch);
//
//                if (FALSE === $ret || !empty($err)) {
//                    $errno = curl_errno($ch);
//                    $info = curl_getinfo($ch);
//                    logging_run(array('colin7777' => $err));
//                } else {
//                    isetcookie('__lineLoginInfo', urlencode($ret), 70 * 86400);//可用
//                    logging_run(array('colin8811' => $ret));
//                    $ret = json_decode($ret, true);
//                    logging_run(array('colin8889' => $ret));
//                    // {userId=Ua2b67a5b7ac9d3923a9ec04cc6dc7250; displayName=Miro Lu@TW; pictureUrl=https://profile.line-scdn.net/0h9k2ANZVJZkQPOEzIqZEZEzN9aCl4FmAMd14hKn5qbCRyXShGMl17IH9tMHMiACZHYQ4vdX09bXFy; }
//                    $_SESSION['lineLoginInfo'] = "sddfefe1000";//没用
//                }
//
//                curl_close($ch);
////        isetcookie('__lineLoginInfo', urlencode($ret), 7 * 86400);//可用
//
//                $login_redirect_uri = $_W['siteroot']."/app/index.php?i=2&c=entry&m=ewei_shopv2&do=mobile";
//                if (strpos($_W['siteroot'], 'localmuzi') === false) {
//                    $login_redirect_uri = $_W['siteroot']."/shop";
//                }
//                $redirect = pdo_get("ewei_shop_redirect", array("ip" => CLIENT_IP));
//
//                logging_run(array('M8666' => CLIENT_IP));
//
//                if ($redirect) {
//                    if (strpos($redirect['url'], "http") === false ) {
//                        $login_redirect_uri = $_W['siteroot']."/app/".$redirect['url'];
//                        $login_redirect_uri = str_replace('/./', '/', $login_redirect_uri);
//
//                        logging_run(array('M86661' => $redirect['url']));
//                    } else {
//                        $login_redirect_uri = $redirect['url'];
//                        logging_run(array('M86662' => $redirect['url']));
//                    }
//                }
//
//                $login_redirect_uri2 = "";
//                if (isset($_GPC['__login_redirect_uri']) && strlen($_GPC['__login_redirect_uri']) > 6) {
//                    $login_redirect_uri2 = $_W['siteroot']."/app/".urldecode($_GPC['__login_redirect_uri']);
//                    $login_redirect_uri2 = str_replace('/./', '/', $login_redirect_uri2);
//                }
//
//
//                header('Location: '.$login_redirect_uri);
//
//                logging_run(array('A0000n666' => $_GPC));
//
//                logging_run(array('A0000'=>$login_redirect_uri, 'A0001'=>$login_redirect_uri2));
//            }
//            echo 'ffefe1';
//        } else {
//            //line 登錄 如果沒有許可
//            logging_run(array('colin666' => $_GPC));
//            $login_redirect_uri = $_W['siteroot']."/app/index.php?i=2&c=entry&m=ewei_shopv2&do=mobile&r=account.login";
//            header('Location: '.$login_redirect_uri);
//
//        }

        echo "linelogin!";
    }

    //http://wu.test/api/line/line_message_send?userId=Ua2b67a5b7ac9d3923a9ec04cc6dc7250&msg=12333
    //https://wu.megotw.com/api/line/line_message_send?userId=Ua2b67a5b7ac9d3923a9ec04cc6dc7250&msg=12333
    public function line_message_send($userId, $msg)
    {
        if (empty($userId) || empty($msg)) {
            $userId = "Ua2b67a5b7ac9d3923a9ec04cc6dc7250";
            $msg = "hello world!";
        }

        $channelAccessToken = "YfzDaRTTdJifl1Rrmoo8/ZV8dgYy6LoqLTkw19TYuiKVJJRQ5UybLrOcl/UNIkDmyW4oJdm319Ue1fswhm7jfihljFQKYdYCkezyJyeTfxaTR5DKWlDamKTY+NhvloWnWL/pPpgp2jhEFO1hVA7bFAdB04t89/1O/w1cDnyilFU=";
        $userIds = [];
        $userIds[] = $userId;
        $payload = [
            'to' => $userIds,
            'messages' => [
                [
                    'type' => 'text',
                    'text' => $msg
                ]
            ]
        ];

        Log::write("SSS " . $userId . " " . $msg, 'notice');

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, 'https://api.line.me/v2/bot/message/multicast');
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Content-Type: application/json',
            'Authorization: Bearer ' . $channelAccessToken
        ]);
        $linesend = curl_exec($ch);

//        if (isset($linesend['message'])) {
//            Log::write("SSS0 = " . $linesend['message'], 'notice');
//        } else {
//            Log::write("SSS1 = " . $linesend, 'notice');
//        }

        $message = "err";
//        http://newrural.localmuzi.com/linesend.php
        //没有返回值就是发送成功了
        if ($linesend) {
            $linesend = json_decode($linesend, true);
            if (isset($linesend['message']) && strlen($linesend['message']) > 6) {
                //发送失败
                $message = $linesend['message'];
            } else {
                //发送成功
                $message = "ok";
            }
        } else {
            //网络异常  返回值是0， 应该是成功的
            $message = curl_errno($ch);
            Log::write("SSS2 = " . $message, 'notice');
        }
        curl_close($ch);

        $this->success($message);
    }





}





